<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备采集数据编辑器</title>
    <style>
        /* 保持原有样式不变 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            line-height: 1.6;
        }

        /* 顶部导航栏样式 */
        .navbar {
            background-color: #333;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            /* 新增固定定位样式 */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 1000;
            /* 确保导航栏在其他内容上方 */
            box-sizing: border-box;
            /* 防止padding导致宽度溢出 */
        }

        /* 同时给容器添加顶部边距，避免内容被导航栏遮挡 */
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            margin-top: 70px;
            /* 新增，值应略大于导航栏高度 */
        }

        .navbar h1 {
            margin: 0;
            font-size: 1.5rem;
        }

        .navbar-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        /* 主体三栏布局 */
        .main-content {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 20px;
        }

        .sidebar-left {
            flex: 1;
            min-width: 150px;
        }

        .center-area {
            flex: 2;
            min-width: 400px;
        }

        .sidebar-right {
            flex: 1;
            min-width: 300px;
        }

        .section {
            margin: 0 0 20px 0;
            padding: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: white;
        }

        .btn {
            padding: 8px 16px;
            margin: 5px 0;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn:hover {
            background-color: #45a049;
        }

        .btn-danger {
            background-color: #f44336;
        }

        .btn-danger:hover {
            background-color: #d32f2f;
        }

        .form-group {
            margin: 10px 0;
        }

        label {
            display: inline-block;
            width: 120px;
        }

        input,
        textarea,
        select {
            padding: 6px;
            width: 300px;
            box-sizing: border-box;
        }

        textarea {
            height: 100%;
            min-height: 300px;
            width: 100%;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }

        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }

        .error {
            background-color: #f2dede;
            color: #a94442;
        }

        .hidden {
            display: none;
        }

        /* 编辑模态框样式 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 5px;
            width: 500px;
            max-width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }

        /* 响应式调整 */
        @media (max-width: 1024px) {
            .main-content {
                flex-direction: column;
            }

            .sidebar-left,
            .center-area,
            .sidebar-right {
                width: 100%;
                min-width: auto;
            }

            .navbar {
                flex-direction: column;
                align-items: flex-start;
            }

            .navbar-actions {
                margin-top: 10px;
                width: 100%;
            }

            input {
                width: calc(100% - 120px);
            }
        }

        @media (max-width: 600px) {
            label {
                width: 100%;
                margin-bottom: 5px;
            }

            input {
                width: 100%;
            }
        }
    </style>
</head>

<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <h1>设备采集数据编辑器</h1>
        <div class="navbar-actions">
            <button class="btn" id="browseBtn">打开配置文件</button>
            <input type="file" id="fileInput" accept=".json" class="hidden">
            <button class="btn" id="saveBtn">保存配置文件</button>
            <div id="fileStatus" class="status hidden"></div>
        </div>
    </nav>

    <div class="container">
        <div class="main-content">
            <!-- 左边栏：连接信息编辑和设备基本信息编辑 -->
            <aside class="sidebar-left">
                <!-- 新增：连接信息编辑区域 -->
                <div class="section" id="connectionInfoSection">
                    <h2>连接信息编辑</h2>
                    <div class="form-group">
                        <label for="protocol">protocol:</label>
                        <input type="text" id="protocol">
                    </div>
                    <div class="form-group">
                        <label for="server_ip">server_ip:</label>
                        <input type="text" id="server_ip">
                    </div>
                    <div class="form-group">
                        <label for="server_port">server_port:</label>
                        <input type="number" id="server_port">
                    </div>
                    <div class="form-group">
                        <label for="slave_id">slave_id:</label>
                        <input type="number" id="slave_id">
                    </div>
                    <div class="form-group">
                        <label for="timeout">timeout:</label>
                        <input type="number" id="timeout">
                    </div>
                    <div class="form-group">
                        <label for="poll_interval">poll_interval:</label>
                        <input type="number" id="poll_interval">
                    </div>
                    <div class="form-group">
                        <label for="cycle_delay">cycle_delay:</label>
                        <input type="number" id="cycle_delay">
                    </div>
                    <div class="form-group">
                        <label for="retry_delay">retry_delay:</label>
                        <input type="number" id="retry_delay">
                    </div>
                    <div class="form-group">
                        <label for="retry_count">retry_count:</label>
                        <input type="number" id="retry_count">
                    </div>
                </div>

                <div class="section" id="basicInfoSection">
                    <h2>设备基本信息编辑</h2>
                    <div class="form-group">
                        <label for="equip">equip:</label>
                        <input type="text" id="equip">
                    </div>
                    <div class="form-group">
                        <label for="type">type:</label>
                        <input type="text" id="type">
                    </div>
                    <div class="form-group">
                        <label for="id">id:</label>
                        <input type="text" id="id">
                    </div>
                    <div class="form-group">
                        <label for="name">Name:</label>
                        <input type="text" id="name">
                    </div>
                    <div class="form-group">
                        <label for="plc_model">plc_model:</label>
                        <input type="text" id="plc_model">
                    </div>
                </div>
            </aside>

            <!-- 中间区域：数组管理（List + Parameters） -->
            <main class="center-area">
                <!-- List数组管理 -->
                <div class="section" id="listSection">
                    <h2>通信数据（List）管理</h2>
                    <button class="btn" id="addItemBtn">添加新项</button>

                    <h3>通信数据列表</h3>
                    <table id="listTable">
                        <thead>
                            <tr>
                                <th>type</th>
                                <th>addr</th>
                                <th>name_cn</th>
                                <th>name_en</th>
                                <th>len</th>
                                <th>reg</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="listTableBody">
                            <!-- 表格内容将通过JS动态生成 -->
                        </tbody>
                    </table>
                </div>

                <!-- Parameters数组管理 -->
                <div class="section" id="parametersSection">
                    <h2>控制参数（Parameters）管理</h2>
                    <button class="btn" id="addParameterBtn">添加新项</button>

                    <h3>控制参数列表</h3>
                    <table id="parametersTable">
                        <thead>
                            <tr>
                                <th>type</th>
                                <th>addr</th>
                                <th>name_cn</th>
                                <th>name_en</th>
                                <th>len</th>
                                <th>reg</th>
                                <th>default</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="parametersTableBody">
                            <!-- 表格内容将通过JS动态生成 -->
                        </tbody>
                    </table>
                </div>
            </main>

            <!-- 右边栏：JSON内容预览 -->
            <aside class="sidebar-right">
                <div class="section">
                    <h2>JSON内容预览</h2>
                    <div class="form-group">
                        <textarea id="jsonPreview" readonly></textarea>
                    </div>
                    <div id="jsonValidity" class="status hidden"></div>
                </div>
            </aside>
        </div>
    </div>

    <!-- 编辑List项的模态框 -->
    <div id="listEditModal" class="modal">
        <div class="modal-content">
            <h3 id="listModalTitle">编辑通信List项</h3>
            <input type="hidden" id="listEditIndex">

            <div class="form-group">
                <label for="listEditType">type:</label>
                <input type="text" id="listEditType">
            </div>
            <div class="form-group">
                <label for="listEditAddr">addr:</label>
                <input type="text" id="listEditAddr" placeholder="用逗号分隔多个值，如: 76,78,80">
            </div>
            <div class="form-group">
                <label for="listEditNameCn">name_cn:</label>
                <input type="text" id="listEditNameCn">
            </div>
            <div class="form-group">
                <label for="listEditNameEn">name_en:</label>
                <input type="text" id="listEditNameEn">
            </div>
            <div class="form-group">
                <label for="listEditLen">len:</label>
                <input type="text" id="listEditLen">
            </div>
            <div class="form-group">
                <label for="listEditReg">reg:</label>
                <input type="text" id="listEditReg">
            </div>
            <div class="form-group">
                <label for="listEditComment">comment:</label>
                <input type="text" id="listEditComment">
            </div>

            <button class="btn" id="listSaveEditBtn">保存</button>
            <button class="btn btn-danger" id="listCancelEditBtn">取消</button>
        </div>
    </div>

    <!-- 编辑Parameters项的模态框 -->
    <div id="paramEditModal" class="modal">
        <div class="modal-content">
            <h3 id="paramModalTitle">编辑控制Parameters项</h3>
            <input type="hidden" id="paramEditIndex">

            <div class="form-group">
                <label for="paramEditType">type:</label>
                <input type="text" id="paramEditType">
            </div>
            <div class="form-group">
                <label for="paramEditAddr">addr:</label>
                <input type="text" id="paramEditAddr" placeholder="用逗号分隔多个值，如: 10,11">
            </div>
            <div class="form-group">
                <label for="paramEditNameCn">name_cn:</label>
                <input type="text" id="paramEditNameCn">
            </div>
            <div class="form-group">
                <label for="paramEditNameEn">name_en:</label>
                <input type="text" id="paramEditNameEn">
            </div>
            <div class="form-group">
                <label for="paramEditLen">len:</label>
                <input type="text" id="paramEditLen">
            </div>
            <div class="form-group">
                <label for="paramEditReg">reg:</label>
                <input type="text" id="paramEditReg">
            </div>
            <div class="form-group">
                <label for="paramEditDefault">default:</label>
                <input type="text" id="paramEditDefault">
            </div>
            <div class="form-group">
                <label for="paramEditMin">min:</label>
                <input type="text" id="paramEditMin">
            </div>
            <div class="form-group">
                <label for="paramEditMax">max:</label>
                <input type="text" id="paramEditMax">
            </div>
            <div class="form-group">
                <label for="paramEditUnit">unit:</label>
                <input type="text" id="paramEditUnit">
            </div>
            <div class="form-group">
                <label for="paramEditComment">comment:</label>
                <input type="text" id="paramEditComment">
            </div>

            <button class="btn" id="paramSaveEditBtn">保存</button>
            <button class="btn btn-danger" id="paramCancelEditBtn">取消</button>
        </div>
    </div>

    <script>
        // 存储当前JSON数据
        let currentJsonData = null;
        let originalFileName = "dataconfig_modbus.json";

        // DOM元素 - 连接信息
        const protocolInput = document.getElementById('protocol');
        const serverIpInput = document.getElementById('server_ip');
        const serverPortInput = document.getElementById('server_port');
        const slaveIdInput = document.getElementById('slave_id');
        const timeoutInput = document.getElementById('timeout');
        const pollIntervalInput = document.getElementById('poll_interval');
        const cycleDelayInput = document.getElementById('cycle_delay');
        const retryDelayInput = document.getElementById('retry_delay');
        const retryCountInput = document.getElementById('retry_count');

        // DOM元素 - 基础信息
        const browseBtn = document.getElementById('browseBtn');
        const fileInput = document.getElementById('fileInput');
        const saveBtn = document.getElementById('saveBtn');
        const fileStatus = document.getElementById('fileStatus');
        const equipInput = document.getElementById('equip');
        const typeInput = document.getElementById('type');
        const idInput = document.getElementById('id');
        const nameInput = document.getElementById('name');
        const plcModelInput = document.getElementById('plc_model'); // 新增plc_model字段
        const jsonPreview = document.getElementById('jsonPreview');
        const jsonValidity = document.getElementById('jsonValidity');

        // DOM元素 - List数组
        const addItemBtn = document.getElementById('addItemBtn');
        const listTableBody = document.getElementById('listTableBody');
        const listEditModal = document.getElementById('listEditModal');
        const listModalTitle = document.getElementById('listModalTitle');
        const listEditIndex = document.getElementById('listEditIndex');
        const listEditType = document.getElementById('listEditType');
        const listEditAddr = document.getElementById('listEditAddr');
        const listEditNameCn = document.getElementById('listEditNameCn');
        const listEditNameEn = document.getElementById('listEditNameEn');
        const listEditLen = document.getElementById('listEditLen');
        const listEditReg = document.getElementById('listEditReg');
        const listEditComment = document.getElementById('listEditComment');
        const listSaveEditBtn = document.getElementById('listSaveEditBtn');
        const listCancelEditBtn = document.getElementById('listCancelEditBtn');

        // DOM元素 - Parameters数组
        const addParameterBtn = document.getElementById('addParameterBtn');
        const parametersTableBody = document.getElementById('parametersTableBody');
        const paramEditModal = document.getElementById('paramEditModal');
        const paramModalTitle = document.getElementById('paramModalTitle');
        const paramEditIndex = document.getElementById('paramEditIndex');
        const paramEditType = document.getElementById('paramEditType');
        const paramEditAddr = document.getElementById('paramEditAddr');
        const paramEditNameCn = document.getElementById('paramEditNameCn');
        const paramEditNameEn = document.getElementById('paramEditNameEn');
        const paramEditLen = document.getElementById('paramEditLen');
        const paramEditReg = document.getElementById('paramEditReg');
        const paramEditDefault = document.getElementById('paramEditDefault');
        const paramEditMin = document.getElementById('paramEditMin');
        const paramEditMax = document.getElementById('paramEditMax');
        const paramEditUnit = document.getElementById('paramEditUnit');
        const paramEditComment = document.getElementById('paramEditComment');
        const paramSaveEditBtn = document.getElementById('paramSaveEditBtn');
        const paramCancelEditBtn = document.getElementById('paramCancelEditBtn');

        browseBtn.addEventListener('click', () => {
            fileInput.click(); // 触发文件选择对话框
        });

        // 读取文件
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) return;

            originalFileName = file.name;

            const reader = new FileReader();
            reader.onload = (event) => {
                try {
                    currentJsonData = JSON.parse(event.target.result);
                    // 初始化数组（防止文件中无该字段）
                    if (!currentJsonData.list) currentJsonData.list = [];
                    if (!currentJsonData.parameters) currentJsonData.parameters = [];
                    if (!currentJsonData.connection) currentJsonData.connection = {}; // 初始化connection
                    updateUI();
                    showStatus(fileStatus, `成功读取文件: ${file.name}`, 'success');
                    validateJson();
                } catch (error) {
                    showStatus(fileStatus, `文件解析错误: ${error.message}`, 'error');
                    currentJsonData = null;
                }
            };
            reader.readAsText(file);
        });

        // 保存文件
        saveBtn.addEventListener('click', () => {
            if (!currentJsonData) {
                showStatus(fileStatus, '没有可保存的数据，请先读取文件', 'error');
                return;
            }

            // 更新数据
            updateJsonDataFromUI();

            // 检查JSON有效性
            if (!validateJson()) {
                return;
            }

            // 询问用户是否覆盖或重命名
            const action = confirm(`检测到可能存在同名文件"${originalFileName}"\n是否覆盖原文件？\n取消则将提示输入新文件名`);

            let fileName;
            if (action) {
                fileName = originalFileName;
            } else {
                const newName = prompt("请输入新文件名：", originalFileName);
                if (!newName) {
                    showStatus(fileStatus, "取消保存", 'error');
                    return;
                }
                fileName = newName.endsWith(".json") ? newName : `${newName}.json`;
            }

            // 生成JSON字符串
            const jsonString = JSON.stringify(currentJsonData, null, 2);
            const blob = new Blob([jsonString], { type: 'application/json' });
            const url = URL.createObjectURL(blob);

            // 创建下载链接
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();

            // 清理
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            showStatus(fileStatus, `文件将以"${fileName}"保存，请在下载对话框中选择原文件目录`, 'success');
        });

        // ===== List数组相关操作 =====
        // 添加新List项
        addItemBtn.addEventListener('click', () => {
            if (!currentJsonData) {
                showStatus(fileStatus, '请先读取文件', 'error');
                return;
            }

            // 重置编辑表单
            listModalTitle.textContent = "添加新List项";
            listEditIndex.value = "-1";
            listEditType.value = "";
            listEditAddr.value = "";
            listEditNameCn.value = "";
            listEditNameEn.value = "";
            listEditLen.value = "";
            listEditReg.value = "";
            listEditComment.value = "";

            // 显示模态框
            listEditModal.style.display = "flex";
        });

        // 保存List项编辑
        listSaveEditBtn.addEventListener('click', () => {
            const index = parseInt(listEditIndex.value);
            const addrValue = listEditAddr.value.trim();
            const addr = addrValue ? addrValue.split(',').map(item => parseInt(item.trim())) : [];

            const newItem = {
                type: listEditType.value.trim(),
                addr: addr,
                name_cn: listEditNameCn.value.trim(),
                name_en: listEditNameEn.value.trim(),
                len: listEditLen.value.trim(),
                reg: listEditReg.value.trim(),
                comment: listEditComment.value.trim()
            };

            // 添加新项或更新现有项
            if (index === -1) {
                currentJsonData.list.push(newItem);
            } else {
                currentJsonData.list[index] = newItem;
            }

            // 更新UI
            updateListTable();
            updateJsonPreview();
            validateJson();

            // 关闭模态框
            listEditModal.style.display = "none";
        });

        // 取消List项编辑
        listCancelEditBtn.addEventListener('click', () => {
            listEditModal.style.display = "none";
        });

        // ===== Parameters数组相关操作 =====
        // 添加新Parameters项
        addParameterBtn.addEventListener('click', () => {
            if (!currentJsonData) {
                showStatus(fileStatus, '请先读取文件', 'error');
                return;
            }

            // 重置编辑表单
            paramModalTitle.textContent = "添加新Parameters项";
            paramEditIndex.value = "-1";
            paramEditType.value = "";
            paramEditAddr.value = "";
            paramEditNameCn.value = "";
            paramEditNameEn.value = "";
            paramEditLen.value = "";
            paramEditReg.value = "";
            paramEditDefault.value = "";
            paramEditMin.value = "";
            paramEditMax.value = "";
            paramEditUnit.value = "";
            paramEditComment.value = "";

            // 显示模态框
            paramEditModal.style.display = "flex";
        });

        // 保存Parameters项编辑
        paramSaveEditBtn.addEventListener('click', () => {
            const index = parseInt(paramEditIndex.value);
            const addrValue = paramEditAddr.value.trim();
            const addr = addrValue ? addrValue.split(',').map(item => parseInt(item.trim())) : [];

            // 处理数字类型字段（default/min/max）
            const parseNumber = (value) => {
                if (!value.trim()) return undefined;
                const num = Number(value);
                return isNaN(num) ? value : num;
            };

            const newItem = {
                type: paramEditType.value.trim(),
                addr: addr,
                name_cn: paramEditNameCn.value.trim(),
                name_en: paramEditNameEn.value.trim(),
                len: paramEditLen.value.trim(),
                reg: paramEditReg.value.trim(),
                default: parseNumber(paramEditDefault.value),
                min: parseNumber(paramEditMin.value),
                max: parseNumber(paramEditMax.value),
                unit: paramEditUnit.value.trim() || undefined,
                comment: paramEditComment.value.trim() || undefined
            };

            // 移除空值字段
            Object.keys(newItem).forEach(key => {
                if (newItem[key] === undefined || newItem[key] === '') delete newItem[key];
            });

            // 添加新项或更新现有项
            if (index === -1) {
                currentJsonData.parameters.push(newItem);
            } else {
                currentJsonData.parameters[index] = newItem;
            }

            // 更新UI
            updateParametersTable();
            updateJsonPreview();
            validateJson();

            // 关闭模态框
            paramEditModal.style.display = "none";
        });

        // 取消Parameters项编辑
        paramCancelEditBtn.addEventListener('click', () => {
            paramEditModal.style.display = "none";
        });

        // 更新UI显示
        function updateUI() {
            if (!currentJsonData) return;

            // 更新连接信息
            const connection = currentJsonData.connection || {};
            protocolInput.value = connection.protocol || '';
            serverIpInput.value = connection.server_ip || '';
            serverPortInput.value = connection.server_port || '';
            slaveIdInput.value = connection.slave_id || '';
            timeoutInput.value = connection.timeout || '';
            pollIntervalInput.value = connection.poll_interval || '';
            cycleDelayInput.value = connection.cycle_delay || '';
            retryDelayInput.value = connection.retry_delay || '';
            retryCountInput.value = connection.retry_count || '';

            // 更新基本信息
            equipInput.value = currentJsonData.equip || '';
            typeInput.value = currentJsonData.type || '';
            idInput.value = currentJsonData.id || '';
            nameInput.value = currentJsonData.Name || '';
            plcModelInput.value = currentJsonData.plc_model || ''; // 新增plc_model字段

            // 更新列表
            updateListTable();
            updateParametersTable();

            // 更新JSON预览
            updateJsonPreview();
        }

        // 更新List表格
        function updateListTable() {
            if (!currentJsonData || !currentJsonData.list) return;

            listTableBody.innerHTML = '';

            currentJsonData.list.forEach((item, index) => {
                const row = document.createElement('tr');

                row.innerHTML = `
                    <td>${item.type || ''}</td>
                    <td>${item.addr ? item.addr.join(',') : ''}</td>
                    <td>${item.name_cn || ''}</td>
                    <td>${item.name_en || ''}</td>
                    <td>${item.len || ''}</td>
                    <td>${item.reg || ''}</td>
                    <td>
                        <button class="btn" onclick="editListItem(${index})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteListItem(${index})">删除</button>
                    </td>
                `;

                listTableBody.appendChild(row);
            });
        }

        // 更新Parameters表格
        function updateParametersTable() {
            if (!currentJsonData || !currentJsonData.parameters) return;

            parametersTableBody.innerHTML = '';

            currentJsonData.parameters.forEach((item, index) => {
                const row = document.createElement('tr');

                row.innerHTML = `
                    <td>${item.type || ''}</td>
                    <td>${item.addr ? item.addr.join(',') : ''}</td>
                    <td>${item.name_cn || ''}</td>
                    <td>${item.name_en || ''}</td>
                    <td>${item.len || ''}</td>
                    <td>${item.reg || ''}</td>
                    <td>${item.default !== undefined ? item.default : ''}</td>
                    <td>
                        <button class="btn" onclick="editParameterItem(${index})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteParameterItem(${index})">删除</button>
                    </td>
                `;

                parametersTableBody.appendChild(row);
            });
        }

        // 更新JSON预览
        function updateJsonPreview() {
            if (!currentJsonData) return;

            updateJsonDataFromUI();
            jsonPreview.value = JSON.stringify(currentJsonData, null, 2);
        }

        // 从UI更新JSON数据
        function updateJsonDataFromUI() {
            if (!currentJsonData) return;

            // 更新连接信息
            if (!currentJsonData.connection) currentJsonData.connection = {};
            currentJsonData.connection.protocol = protocolInput.value.trim() || undefined;
            currentJsonData.connection.server_ip = serverIpInput.value.trim() || undefined;
            currentJsonData.connection.server_port = serverPortInput.value ? parseInt(serverPortInput.value) : undefined;
            currentJsonData.connection.slave_id = slaveIdInput.value ? parseInt(slaveIdInput.value) : undefined;
            currentJsonData.connection.timeout = timeoutInput.value ? parseInt(timeoutInput.value) : undefined;
            currentJsonData.connection.poll_interval = pollIntervalInput.value ? parseInt(pollIntervalInput.value) : undefined;
            currentJsonData.connection.cycle_delay = cycleDelayInput.value ? parseInt(cycleDelayInput.value) : undefined;
            currentJsonData.connection.retry_delay = retryDelayInput.value ? parseInt(retryDelayInput.value) : undefined;
            currentJsonData.connection.retry_count = retryCountInput.value ? parseInt(retryCountInput.value) : undefined;

            // 更新基本信息
            currentJsonData.equip = equipInput.value.trim() || undefined;
            currentJsonData.type = typeInput.value.trim() || undefined;
            currentJsonData.id = idInput.value.trim() || undefined;
            currentJsonData.Name = nameInput.value.trim() || undefined;
            currentJsonData.plc_model = plcModelInput.value.trim() || undefined; // 新增plc_model字段
        }

        // 编辑List项
        window.editListItem = function (index) {
            if (!currentJsonData || !currentJsonData.list || index < 0 || index >= currentJsonData.list.length) {
                return;
            }

            const item = currentJsonData.list[index];

            listModalTitle.textContent = "编辑List项";
            listEditIndex.value = index;
            listEditType.value = item.type || '';
            listEditAddr.value = item.addr ? item.addr.join(',') : '';
            listEditNameCn.value = item.name_cn || '';
            listEditNameEn.value = item.name_en || '';
            listEditLen.value = item.len || '';
            listEditReg.value = item.reg || '';
            listEditComment.value = item.comment || '';

            listEditModal.style.display = "flex";
        };

        // 删除List项
        window.deleteListItem = function (index) {
            if (!currentJsonData || !currentJsonData.list || index < 0 || index >= currentJsonData.list.length) {
                return;
            }

            if (confirm("确定要删除这项吗？")) {
                currentJsonData.list.splice(index, 1);
                updateListTable();
                updateJsonPreview();
                validateJson();
            }
        };

        // 编辑Parameters项
        window.editParameterItem = function (index) {
            if (!currentJsonData || !currentJsonData.parameters || index < 0 || index >= currentJsonData.parameters.length) {
                return;
            }

            const item = currentJsonData.parameters[index];

            paramModalTitle.textContent = "编辑Parameters项";
            paramEditIndex.value = index;
            paramEditType.value = item.type || '';
            paramEditAddr.value = item.addr ? item.addr.join(',') : '';
            paramEditNameCn.value = item.name_cn || '';
            paramEditNameEn.value = item.name_en || '';
            paramEditLen.value = item.len || '';
            paramEditReg.value = item.reg || '';
            paramEditDefault.value = item.default !== undefined ? item.default : '';
            paramEditMin.value = item.min !== undefined ? item.min : '';
            paramEditMax.value = item.max !== undefined ? item.max : '';
            paramEditUnit.value = item.unit || '';
            paramEditComment.value = item.comment || '';

            paramEditModal.style.display = "flex";
        };

        // 删除Parameters项
        window.deleteParameterItem = function (index) {
            if (!currentJsonData || !currentJsonData.parameters || index < 0 || index >= currentJsonData.parameters.length) {
                return;
            }

            if (confirm("确定要删除这项吗？")) {
                currentJsonData.parameters.splice(index, 1);
                updateParametersTable();
                updateJsonPreview();
                validateJson();
            }
        };

        // 显示状态信息
        function showStatus(element, message, type) {
            element.textContent = message;
            element.className = `status ${type}`;
            element.classList.remove('hidden');

            // 3秒后自动隐藏
            setTimeout(() => {
                element.classList.add('hidden');
            }, 3000);
        }

        // 验证JSON格式
        function validateJson() {
            try {
                // 尝试解析以验证格式
                JSON.parse(JSON.stringify(currentJsonData));
                showStatus(jsonValidity, "JSON格式有效", 'success');
                return true;
            } catch (error) {
                showStatus(jsonValidity, `JSON格式无效: ${error.message}`, 'error');
                return false;
            }
        }

        // 监听连接信息和基本信息变化，实时更新预览
        [protocolInput, serverIpInput, serverPortInput, slaveIdInput, timeoutInput,
            pollIntervalInput, cycleDelayInput, retryDelayInput, retryCountInput,
            equipInput, typeInput, idInput, nameInput, plcModelInput].forEach(input => {
                input.addEventListener('input', updateJsonPreview);
            });
    </script>
</body>

</html>